# script runs in the night after the daily quotes have been retrieved.
# it scans the market for trading opportunities
strategySignals <- function(verbose=TRUE) {
  dailySignals <- data.frame()
  signalRow <- function(stratname, code, date, direction, duration, atr, atrpct, LL, WL) {
    if (direction=="long") {
      UL = atr*WL
      LL = atr*LL*(-1)
    } else {
      UL = atr*LL
      LL = atr*WL*(-1)
    }
    return (data.frame(
      strategy=stratname,
      code=code,
      date=date,
      direction=direction,
      duration=duration,
      atr=atr,
      atrpct=atrpct,
      UL=UL,
      LL=LL,
      row.names=NULL))
  }
  # read strategy list and determine groups to fetch (grpTF)
  strat <- myStrategies()
  grpTF <-c()
  for (i in 1:length(strat)) {
    thisstrat <- strat[[i]]
    for (j in 1:length(thisstrat$groups)) {
      grpTF <- union(grpTF, thisstrat$groups[[j]][1])      
    }
  }
  groupinfo <- getDBGroup(grpTF)
  # fetch prices from db. starting date at from-date as declared in db
  if (verbose==TRUE) cat(sprintf("Fetching %d Symbols from db\n", nrow(groupinfo)))
  for(i in 1:nrow(groupinfo)) {
    getSymbols(toString(groupinfo[i,'stock_id']), src='vadbID', datefrom=Sys.Date()-1200)
  }
  # loop through all strategies
  for (i in 1:length(strat)) {
    grplist <- strat[[i]]$groups  # contains list of groups incl. LL and WL
    grps <- c()
    LL <- list()
    WL <- list()
    for (ii in 1:length(grplist)) {
      grps <- c(grps, grplist[[ii]][1])         # grps contains group names i.e. c("DJI_STOCKS", "SMALL_CAPS")
      LL[grplist[[ii]][1]] <- as.numeric(grplist[[ii]][2])
      WL[grplist[[ii]][1]] <- as.numeric(grplist[[ii]][3])      
    }
    if (verbose==TRUE) cat("Strategy ", strat[[i]]$name, ": Apply to groups", grps, "\n")
    # loop through all symbols that current strategy is to be applied to
    for (grp in grps) {
      groupinfo <- getDBGroup(grp)
      for (j in 1:nrow(groupinfo)) {
        symcode <- paste(groupinfo[j,'code'], ".vadb", sep="")
        # calculate indicators
        XATR <- ATR(cbind(Hi(get(symcode)), Lo(get(symcode)), Cl(get(symcode))))
        AS <- ADXStatus(get(symcode), addSig=TRUE)
        SMA200 <- SMAStatus(get(symcode), n=200)
        SMA50 <- SMAStatus(get(symcode), n=50)
        # apply rules for current strategy
        if (strat[[i]]$name == "S_ADX_1060") {
          FILTERED <- AS[,'ADXgt25'] & AS[,'sig_DIcu'] & SMA200[,'CltSMA200']          
        } else if (strat[[i]]$name == "S_ADX_4290") {
          FILTERED <- AS[,'ADXnt'] & AS[,'sig_DIcd'] & AS[,'sig_ADXrise'] & SMA50[,'CltSMA50']
        } else if (strat[[i]]$name == "S_GAP_9228") {
          CSPS <- CSPStatus(get(symcode), "GAP")
          FILTERED <- AS[,'ADXgt25'] & AS[,'DIpgt'] & SMA50[,'CltSMA50'] & CSPS[,'GapUp']
        } else if (strat[[i]]$name == "L_DONCHIAN_17428") {
          DCS <- DCStatus(get(symcode), n=10)
          FILTERED <- AS[,'ADXgt25'] & AS[,'DIngt'] & SMA50[,'CltSMA50'] & DCS[,'CltDC10']
        }
        colnames(FILTERED) <- c("EntrySignal")
        #ToDo: check date of last(FILTERED)
        if (last(FILTERED) == TRUE) {
          if (verbose==TRUE) {cat(strat[[i]]$direction, "signal for", groupinfo[j,'code'], "@", as.character.Date(index(last(FILTERED))), "\n")}
          dailySignals <- rbind(dailySignals, signalRow(strat[[i]]$name,
                                                        groupinfo[j,'code'], 
                                                        as.character.Date(index(last(FILTERED))),
                                                        strat[[i]]$direction,
                                                        strat[[i]]$duration,
                                                        as.vector(last(XATR[,'atr'])),
                                                        as.vector(last(XATR[,'atr'])*100/Cl(last(get(symcode)))),
                                                        LL[[grp]],
                                                        WL[[grp]]))
        }
      }
    }
  }
  return (dailySignals)
}